const Database = require('better-sqlite3');
const db = new Database('../db/app.db');


function getAll() {
    const rows = db.prepare('SELECT * FROM tasks').all();
    return rows;
}

function addTask(text, user_id) {
    try {
        db.prepare('INSERT INTO tasks (text, user_id) VALUES (?, ?)')
            .run(text, user_id);
        return { status: 0, msg: 'Task added successfully' };
    } catch (e) {
        return { status: 12, msg: e.message };
    }
}

function removeById(id) {
    try {
        db.prepare('DELETE FROM tasks WHERE id = ?').run(id);
        return { status: 0, msg: 'Task deleted successfully' };
    } catch (e) {
        return { status: 12, msg: e.message };
    }
}

function updateById(id, text) {
    try {
        db.prepare('UPDATE tasks SET text = ? WHERE id = ?').run(text, id);
        return { status: 0, msg: 'Task updated successfully' };
    } catch (e) {
        return { status: 12, msg: e.message };
    }
}

function getTaskById(id) {
    return db.prepare('SELECT * FROM tasks WHERE id = ?').get(id);
}

module.exports = { getAll, addTask, removeById, updateById, getTaskById };